import { BrowserWindow, clipboard, Menu, type WebContents } from 'electron'

const contextMenu = (window: WebContents) => {
  window.on('context-menu', (_, params) => {
    const menuTmpl: Array<{ label: string; click: () => void }> = [
      {
        label: '控制台',
        click() {
          window.openDevTools()
        }
      }
    ]
    if (params.editFlags.canCopy)
      menuTmpl.push({
        label: '复制',
        click() {
          window.copy()
        }
      })
    if (params.editFlags.canCut)
      menuTmpl.push({
        label: '剪切',
        click() {
          window.cut()
        }
      })
    if (params.editFlags.canPaste)
      menuTmpl.push({
        label: '粘贴',
        click() {
          window.paste()
        }
      })
    if (params.linkURL) {
      menuTmpl.push({
        label: '复制链接地址',
        click() {
          clipboard.writeText(params.linkURL)
        }
      })
    }
    if (['image'].indexOf(params.mediaType) > -1) {
      menuTmpl.push({
        label: '复制图片',
        click() {
          window.copyImageAt(params.x, params.y)
        }
      })
    }
    const menu = Menu.buildFromTemplate(menuTmpl)
    const { x, y } = params
    menu.popup({ window: BrowserWindow.fromWebContents(window)!, x, y })
  })
}

export default contextMenu
